class FileStorageClient:
    def __init__(self, base_url):
        self.base_url = base_url
        self.session = requests.Session()

    def push_file(self, local_path, remote_path):
        """上传本地文件到服务端，分块上传（每次10MB）"""
        try:
            with open(local_path, 'rb') as f:
                offset = 0
                chunk_size = 10 * 1024 * 1024  # 10 MB

                while True:
                    f.seek(offset)
                    chunk = f.read(chunk_size)
                    if not chunk:
                        break

                    url = f"{self.base_url}/write"
                    data = {
                        "path": remote_path,
                        "offset": offset,
                        "data": base64.b64encode(chunk).decode('utf-8'),
                        "length": len(chunk)
                    }

                    response = self.session.post(url, json=data)
                    result = response.json()

                    if result.get("status") != 0:
                        print("上传失败:", result.get("statusText"))
                        return False

                    print(f"已写入 {len(chunk)} 字节，偏移量: {offset}")
                    offset += len(chunk)

                return True
        except Exception as e:
            print("上传异常:", str(e))
            return False

    def pull_file(self, remote_path, local_path):
        """从服务端下载文件并保存为本地文件，分块下载（每次10MB）"""
        try:
            offset = 0
            chunk_size = 10 * 1024 * 1024  # 10 MB

            with open(local_path, 'wb') as f:
                while True:
                    url = f"{self.base_url}/read"
                    data = {
                        "path": remote_path,
                        "offset": offset,
                        "length": chunk_size
                    }

                    response = self.session.post(url, json=data)
                    result = response.json()

                    if result.get("status") != 0:
                        print("下载失败:", result.get("statusText"))
                        return False

                    encoded_data = result.get("data")
                    if not encoded_data:
                        print("接收到空数据，可能是文件已读完。")
                        break

                    chunk = base64.b64decode(encoded_data)
                    f.write(chunk)

                    print(f"已接收并写入 {len(chunk)} 字节，总大小: {offset + len(chunk)}")
                    offset += len(chunk)

                    if len(chunk) < chunk_size:
                        break

            print(f"文件下载完成，保存路径：{local_path}")
            return True
        except Exception as e:
            print("下载异常:", str(e))
            return False

    def push_data(self, data: bytes, remote_path):
        """将内存中的 bytes 数据上传到服务端，分块上传"""
        try:
            offset = 0
            chunk_size = 10 * 1024 * 1024  # 10 MB
            total_size = len(data)

            while offset < total_size:
                end = min(offset + chunk_size, total_size)
                chunk = data[offset:end]

                url = f"{self.base_url}/write"
                payload = {
                    "path": remote_path,
                    "offset": offset,
                    "data": base64.b64encode(chunk).decode('utf-8'),
                    "length": len(chunk)
                }

                response = self.session.post(url, json=payload)
                result = response.json()

                if result.get("status") != 0:
                    print("上传失败:", result.get("statusText"))
                    return False

                print(f"已写入 {len(chunk)} 字节，偏移量: {offset}")
                offset += len(chunk)

            return True
        except Exception as e:
            print("上传异常:", str(e))
            return False

    def pull_data(self, remote_path):
        """从服务端拉取文件内容到内存中的 bytes"""
        try:
            data = b''
            offset = 0
            chunk_size = 10 * 1024 * 1024  # 10 MB

            while True:
                url = f"{self.base_url}/read"
                payload = {
                    "path": remote_path,
                    "offset": offset,
                    "length": chunk_size
                }

                response = self.session.post(url, json=payload)
                result = response.json()

                if result.get("status") != 0:
                    print("下载失败:", result.get("statusText"))
                    return None

                encoded_data = result.get("data")
                if not encoded_data:
                    print("接收到空数据，可能是文件已读完。")
                    break

                chunk = base64.b64decode(encoded_data)
                data += chunk

                print(f"已接收 {len(chunk)} 字节，总大小: {len(data)}")
                offset += len(chunk)

                if len(chunk) < chunk_size:
                    break

            print(f"数据下载完成，总大小: {len(data)} 字节")
            return data
        except Exception as e:
            print("下载异常:", str(e))
            return None